package com.yanqu.road.logic.activity.evefeast;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.evefeast.EveFeastGameData;
import com.yanqu.road.entity.activity.evefeast.EveFeastItem;
import com.yanqu.road.entity.activity.evefeast.config.*;
import com.yanqu.road.logic.activity.evefeast.enums.eEveFeastBuffType;
import com.yanqu.road.pb.activity.EveFeastProto;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class EveFeastConfig {
    private int activityId;

    public EveFeastConfig(int activityId) {
        this.activityId = activityId;
    }

    private Map<String, EveFeastProto.EveFeastConfigSyncMsg> configMsgMap = new ConcurrentHashMap<>();

    /**
     * 战令1效果参数 相国印（每局额外获得刷新次数|移除次数|雅趣值加成千分比）
     */
    private List<Integer> token1Params = new ArrayList<>();
    /**
     * 战令2效果参数 帝王印（每局额外获得刷新次数|移除次数|雅趣值加成千分比）
     */
    private List<Integer> token2Params = new ArrayList<>();

    /**
     * 次数回复消耗
     */
    private Property energyCost = new Property();
    /**
     * 每天次数
     */
    private int dayNum = 5;
    /**
     * 单局积分评价列表
     */
    private List<Integer> scoreAppraiseList = new ArrayList<>();
    /**
     * 评价奖励
     */
    private List<Property> appraiseRewardList = new ArrayList<>();
    /**
     * 消除道具,活动结束回收
     */
    private int eliminateItemId = 123391;
    /**
     * 刷新道具,活动结束回收
     */
    private int refreshItemId = 123392;
    /**
     * 初始道具
     */
    private List<Integer> initItemIdList = new ArrayList<>();
    /**
     * 试玩关卡的初始道具
     */
    private List<Integer> tryInitItemIdList = new ArrayList<>();
    /**
     * 局内道具配置
     */
    private Map<Integer, EveFeastObjectConfig> objectConfigMap = new HashMap<>();
    private Map<Integer, List<EveFeastObjectConfig>> objectListMapByQuality = new HashMap<>();
    /**
     * 祝酒词配置
     */
    private Map<Integer, EveFeastBuffConfig> buffConfigMap = new HashMap<>();
    /**
     * 关卡配置
     */
    private Map<Integer, EveFeastMissionConfig> missionConfigMap = new HashMap<>();
    private Map<Integer, List<EveFeastMissionConfig>> missionConfigByMissionMap = new HashMap<>();
    /**
     * 局内成就配置
     */
    private Map<Integer, EveFeastAchieveConfig> achieveConfigMap = new HashMap<>();

    /**
     * 需要回收的道具
     */
    private List<Integer> recycleItemList = new ArrayList<>();

    /**
     * 新手引导需要的盘面
     */
    private List<Property> guideSceneProperty = new ArrayList<>();

    /**
     * 新手引导需要的初始选择物品
     */
    private List<List<Integer>> guideInitSelectItemList = new ArrayList<>();

    /**
     * 高级战令随机池
     */
    private Map<Integer, Integer> token2RandomPool = new HashMap<>();

    public void setEnergyCost(Property energyCost) {
        this.energyCost = energyCost;
    }

    public void setDayNum(int dayNum) {
        this.dayNum = dayNum;
    }

    public void setScoreAppraiseList(List<Integer> scoreAppraiseList) {
        this.scoreAppraiseList = scoreAppraiseList;
    }

    public void setAppraiseRewardList(List<Property> appraiseRewardList) {
        this.appraiseRewardList = appraiseRewardList;
    }

    public void setEliminateItemId(int eliminateItemId) {
        this.eliminateItemId = eliminateItemId;
    }

    public void setRefreshItemId(int refreshItemId) {
        this.refreshItemId = refreshItemId;
    }


    public void setObjectConfigMap(Map<Integer, EveFeastObjectConfig> objectConfigMap) {
        this.objectConfigMap = objectConfigMap;
        for (EveFeastObjectConfig objectConfig : this.objectConfigMap.values()) {
            objectConfig.initTriggerInfo();
            List<EveFeastObjectConfig> list = this.objectListMapByQuality.get(objectConfig.getQuality());
            if (list == null) {
                list = new ArrayList<>();
                this.objectListMapByQuality.put(objectConfig.getQuality(), list);
            }
            list.add(objectConfig);
        }
    }

    public void setBuffConfigMap(Map<Integer, EveFeastBuffConfig> buffConfigMap) {
        this.buffConfigMap = buffConfigMap;
    }

    public void setMissionConfigMap(Map<Integer, EveFeastMissionConfig> missionConfigMap) {
        this.missionConfigMap = missionConfigMap;

        Map<Integer, List<EveFeastMissionConfig>> missionConfigByMissionMap = new HashMap<>();
        for (EveFeastMissionConfig missionConfig : this.missionConfigMap.values()) {
            List<EveFeastMissionConfig> list = missionConfigByMissionMap.get(missionConfig.getMission());
            if (list == null) {
                list = new ArrayList<>();
                missionConfigByMissionMap.put(missionConfig.getMission(), list);
            }
            list.add(missionConfig);
        }
        setMissionConfigByMissionMap(missionConfigByMissionMap);
    }

    public void setMissionConfigByMissionMap(Map<Integer, List<EveFeastMissionConfig>> missionConfigByMissionMap) {
        this.missionConfigByMissionMap = missionConfigByMissionMap;
    }

    public void setAchieveConfigMap(Map<Integer, EveFeastAchieveConfig> achieveConfigMap) {
        this.achieveConfigMap = achieveConfigMap;
    }

    public int getActivityId() {
        return activityId;
    }

    public Property getEnergyCost() {
        return energyCost;
    }

    public int getDayNum() {
        return dayNum;
    }

    public List<Integer> getScoreAppraiseList() {
        return scoreAppraiseList;
    }

    public List<Property> getAppraiseRewardList() {
        return appraiseRewardList;
    }

    public int getEliminateItemId() {
        return eliminateItemId;
    }

    public int getRefreshItemId() {
        return refreshItemId;
    }

    public Map<Integer, EveFeastObjectConfig> getObjectConfigMap() {
        return objectConfigMap;
    }

    public Map<Integer, EveFeastBuffConfig> getBuffConfigMap() {
        return buffConfigMap;
    }

    public Map<Integer, EveFeastMissionConfig> getMissionConfigMap() {
        return missionConfigMap;
    }

    public Map<Integer, List<EveFeastMissionConfig>> getMissionConfigByMissionMap() {
        return missionConfigByMissionMap;
    }

    public Map<Integer, EveFeastAchieveConfig> getAchieveConfigMap() {
        return achieveConfigMap;
    }

    public EveFeastAchieveConfig getAchieveConfig(int achieveId) {
        return achieveConfigMap.get(achieveId);
    }

    public void setInitItemIdList(List<Integer> initItemIdList) {
        this.initItemIdList = initItemIdList;
    }

    public List<Integer> getInitItemIdList() {
        return initItemIdList;
    }

    public List<Integer> getTryInitItemIdList() {
        return tryInitItemIdList;
    }

    public void setTryInitItemIdList(List<Integer> tryInitItemIdList) {
        this.tryInitItemIdList = tryInitItemIdList;
    }

    public List<Integer> getRecycleItemList() {
        return recycleItemList;
    }

    public void setRecycleItemList(List<Integer> recycleItemList) {
        this.recycleItemList = recycleItemList;
    }

    /**
     * 初始化活动配置
     *
     * @return
     */
    public void parseConfig(Map<String, ActivityConfig> activityConfigMap) {
        this.setEnergyCost(PropertyHelper.parseStringToProperty(activityConfigMap.get("EVEFEAST_ENERGY_ITEM_ID").getValue()));
        this.setDayNum(Integer.parseInt(activityConfigMap.get("EVEFEAST_ENERGY_MAX_NUM").getValue()));
        this.setScoreAppraiseList(StringUtils.stringToIntegerList(activityConfigMap.get("EVEFEAST_EVALUE_LIMIT").getValue(), "\\|"));
        List<Integer> list = StringUtils.stringToIntegerList(activityConfigMap.get("EVEFEAST_GAME_ITEM_1").getValue(), "\\|");
        this.setEliminateItemId(list.get(0));
        this.setRefreshItemId(list.get(1));
        this.setInitItemIdList(StringUtils.stringToIntegerList(activityConfigMap.get("EVEFEAST_ORIGIN_ITEM").getValue(), "\\|"));
        this.setTryInitItemIdList(StringUtils.stringToIntegerList(activityConfigMap.get("EVEFEAST_ORIGIN_ITEM_TRY").getValue(), "\\|"));
        String[] evefeast_evalue_rewards = activityConfigMap.get("EVEFEAST_EVALUE_REWARD").getValue().split("\\|");
        List<Property> appraiseRewardList = new ArrayList<>();
        for (String evefeast_evalue_reward : evefeast_evalue_rewards) {
            appraiseRewardList.add(PropertyHelper.parseStringToProperty(evefeast_evalue_reward));
        }
        this.setAppraiseRewardList(appraiseRewardList);

        this.setToken1Params(StringUtils.stringToIntegerList(activityConfigMap.get("EVEFEAST_TOKEN_EFFECT_1").getValue(), "\\|"));
        this.setToken2Params(StringUtils.stringToIntegerList(activityConfigMap.get("EVEFEAST_TOKEN_EFFECT_2").getValue(), "\\|"));
        this.setRecycleItemList(StringUtils.stringToIntegerList(activityConfigMap.get("EVEFEAST_RECYCLE_ID").getValue(), "\\|"));
        List<List<Integer>> guideChoseItems = new ArrayList<>();
        for (String evefeast_newguide_item : activityConfigMap.get("EVEFEAST_NEWGUIDE_ITEM").getValue().split("#")) {
            List<Integer> itemIds = StringUtils.stringToIntegerList(evefeast_newguide_item, "\\|");
            guideChoseItems.add(itemIds);
        }
        this.setGuideInitSelectItemList(guideChoseItems);

        List<Property> guidePropertyList = new ArrayList<>();
        for (String evefeast_newguide_scene : activityConfigMap.get("EVEFEAST_NEWGUIDE_SCENE").getValue().split("#")) {
            Property property = PropertyHelper.parseStringToProperty(evefeast_newguide_scene, "\\|");
            guidePropertyList.add(property);
        }
        this.setGuideSceneProperty(guidePropertyList);

        Property token2RandomProperty = PropertyHelper.parseStringToProperty(activityConfigMap.get("EVEFEAST_TOKEN_EFFECT_2_EX").getValue(), "\\|");
        for (Map.Entry<Integer, BigInteger> entry : token2RandomProperty.getGoods().entrySet()) {
            int itemId = entry.getKey();
            int weight = entry.getValue().intValue();
            this.token2RandomPool.put(itemId, weight);
        }
    }

    /**
     * 初始每关的道具权重
     * 先按mission表的mission字段取到object表的权重 为本关物品权重
     * 按物品品质取 mission表的weight字段 为本关物品品质权重系数
     * 物品在本关的权重 = 本关物品权重 * (1+ 为本关物品品质权重系数/1000)
     */
    public void initMissionObjectWeight() {
        for (EveFeastMissionConfig missionConfig : missionConfigMap.values()) {
            Map<Integer, Integer> objectWeightItemMap = new HashMap<>();
            Map<Integer, Integer> buffWeightItemMap = new HashMap<>();
            Map<Integer, Map<Integer, Integer>> objectRandomMapByType = new HashMap<>();
            Map<Integer, Map<Integer, Integer>> buffRandomMapByQuality = new HashMap<>();

            for (EveFeastObjectConfig objectConfig : objectConfigMap.values()) {
                int weightByMission = objectConfig.getWeightByMission(missionConfig.getMission());
                int objectWeightByQuality = missionConfig.getObjectWeightByQuality(objectConfig.getQuality() - 1);
                int weight = BigDecimal.valueOf(weightByMission).multiply(BigDecimal.valueOf(1000).add(BigDecimal.valueOf(objectWeightByQuality))).divide(BigDecimal.valueOf(1000)).intValue();

                objectWeightItemMap.put(objectConfig.getObjectId(), weight);
                Map<Integer, Integer> map = objectRandomMapByType.get(objectConfig.getType());
                if (map == null) {
                    map = new HashMap<>();
                    objectRandomMapByType.put(objectConfig.getType(), map);
                }
                map.put(objectConfig.getObjectId(), weight);
            }

            for (EveFeastBuffConfig buffConfig : buffConfigMap.values()) {
                int weightByMission = buffConfig.getWeightByMission(missionConfig.getMission());
                buffWeightItemMap.put(buffConfig.getGreetingId(), weightByMission);

                Map<Integer, Integer> map = buffRandomMapByQuality.get(buffConfig.getQuality());
                if (map == null) {
                    map = new HashMap<>();
                    buffRandomMapByQuality.put(buffConfig.getQuality(), map);
                }
                map.put(buffConfig.getGreetingId(), weightByMission);
            }

            missionConfig.setObjectWeightMap(objectWeightItemMap);
            missionConfig.setObjectWeightByType(objectRandomMapByType);
            missionConfig.setBuffRandomMap(buffWeightItemMap);
            missionConfig.setBuffRandomMapByQuality(buffRandomMapByQuality);
        }
    }

    public EveFeastProto.EveFeastConfigSyncMsg getConfigMsg(String language) {
        EveFeastProto.EveFeastConfigSyncMsg msg = configMsgMap.get(language);
        return msg;
    }

    public void setConfigMsg(String language, EveFeastProto.EveFeastConfigSyncMsg configMsg) {
        configMsgMap.put(language, configMsg);
    }

    public EveFeastMissionConfig getMissionConfig(int turnId) {
        return missionConfigMap.get(turnId);
    }

    public EveFeastMissionConfig getMissionConfigByTurn(int mission, int turn){
        List<EveFeastMissionConfig> list = missionConfigByMissionMap.get(mission);
        for(EveFeastMissionConfig config : list){
            if(config.getTurn() == turn){
                return config;
            }
        }
        return null;
    }

    public EveFeastObjectConfig getItemConfig(int itemId) {
        return objectConfigMap.get(itemId);
    }

    public EveFeastBuffConfig getBuffConfig(int buffId) {
        return buffConfigMap.get(buffId);
    }

    public List<EveFeastObjectConfig> getObjectListByQuality(int quality) {
        List<EveFeastObjectConfig> list = new ArrayList<>();
        if (objectListMapByQuality.containsKey(quality)) {
            list.addAll(objectListMapByQuality.get(quality));
        }
        return list;
    }

    public int calcEveFeastAppraise(int score) {
        int appraise = 0;
        for (int i = 0; i < scoreAppraiseList.size(); i++) {
            if (score >= scoreAppraiseList.get(i)) {
                appraise = i;
            }
        }
        return appraise;
    }

    public Property getAppraiseReward(int appraise) {
        if (appraise < appraiseRewardList.size()) {
            return new Property(appraiseRewardList.get(appraise));
        }
        return new Property();
    }

    public List<Integer> getToken1Params() {
        return token1Params;
    }

    public void setToken1Params(List<Integer> token1Params) {
        this.token1Params = token1Params;
    }

    public List<Integer> getToken2Params() {
        return token2Params;
    }

    public void setToken2Params(List<Integer> token2Params) {
        this.token2Params = token2Params;
    }

    /**
     * 随机物品列表,不重复随机
     *
     * @param missionConfig
     * @return
     */
    public List<Integer> randomItemList(EveFeastGameData gameData, EveFeastMissionConfig missionConfig, int num) {
        List<Integer> itemList = new ArrayList<>();
        if (missionConfig == null) {
            return itemList;
        }
        Map<Integer, Integer> weightMap = missionConfig.getNewObjectWeightMap();
        //排除当前随机到的物品
        for (Integer itemId : gameData.getChoseItems()) {
            weightMap.remove(itemId);
        }

        //排除限制数量的物品,目前按非0就限制只有一个来处理
        for (EveFeastItem haveItem : gameData.getHaveItems()) {
            EveFeastObjectConfig itemConfig = getItemConfig(haveItem.getItemId());
            if (itemConfig == null) {
                continue;
            }
            if (itemConfig.getLimitNum() == 0) {
                continue;
            }

            weightMap.remove(haveItem.getItemId());
        }

        for (int i = 0; i < num; i++) {
            int itemId = RandomHelper.getRandomKeyByWeight(weightMap);
            weightMap.remove(itemId);
            itemList.add(itemId);
        }

        if (itemList.size() < num) {//池不够随机了,全随机一下
            weightMap = missionConfig.getNewObjectWeightMap();
            for (Integer itemId : itemList) {
                weightMap.remove(itemId);
            }

            for (int i = 0; i < num - itemList.size(); i++) {
                int itemId = RandomHelper.getRandomKeyByWeight(weightMap);
                itemList.add(itemId);
                weightMap.remove(itemId);
            }
        }

        return itemList;
    }

    /**
     * 随机祝酒词,不重复随机
     */
    public List<Integer> randomGreetingId(EveFeastGameData gameData, EveFeastMissionConfig missionConfig, int num) {
        List<Integer> greetingIdList = new ArrayList<>();
        if (missionConfig == null) {
            return greetingIdList;
        }
        //先随机品质
        List<Integer> buffWeightParams = missionConfig.getBuffWeightParams();
        int quality = RandomHelper.getRandomIndexByWeight(buffWeightParams);
        if (quality < 0) {
            return greetingIdList;
        }
        quality += 1;

        //取品质下的所有祝酒词
        Map<Integer, Integer> weightMap = missionConfig.getBuffRandomMapByQuality(quality);

        //排除当前随机到的祝酒词
        for (Integer greetingId : gameData.getChoseBuffs()) {
            weightMap.remove(greetingId);
        }

        //根据已有物品计算新的权重
        for (Integer greetingId : weightMap.keySet()) {
            EveFeastBuffConfig buffConfig = getBuffConfig(greetingId);
            if (buffConfig == null) {
                continue;
            }

            //这里是祝酒词不能添加有数量限制并且已拥有的物品,暂时不用。
//            for (EveFeastBuffInfo eveFeastBuffInfo : buffConfig.getBuffInfoList()) {
//                if (eveFeastBuffInfo.getBuffType() == eEveFeastBuffType.Type4.getValue()) {
//                    //如果添加的是有数量限制的物品,不让随机到
//                    int itemId = eveFeastBuffInfo.getBuffParam(0);
//                    EveFeastObjectConfig itemConfig = getItemConfig(itemId);
//                    if (itemConfig != null && itemConfig.getLimitNum() > 0) {
//                        if (gameData.isItemHave(itemId)) {
//                            weightMap.remove(greetingId);
//                            break;
//                        }
//                    }
//                }
//            }
//
//            if (!weightMap.containsKey(greetingId)) {
//                continue;
//            }

            Property weightChangeProperty = buffConfig.getWeightChangeProperty();
            for (Map.Entry<Integer, BigInteger> entry : weightChangeProperty.getGoods().entrySet()) {
                int checkItemId = entry.getKey();
                int weightAdd = entry.getValue().intValue();
                for (EveFeastItem haveItem : gameData.getHaveItems()) {
                    if (haveItem.getItemId() == checkItemId) {
                        weightMap.put(greetingId, weightMap.get(greetingId) + weightAdd);
                    }
                }
            }
        }

        for (int i = 0; i < num; i++) {
            int greetingId = RandomHelper.getRandomKeyByWeight(weightMap);
            greetingIdList.add(greetingId);
            weightMap.remove(greetingId);
        }

        if (greetingIdList.size() < num) {//池不够了,全随机一下
            weightMap = missionConfig.getBuffRandomMapByQuality(quality);
            for (Integer greetingId : greetingIdList) {
                weightMap.remove(greetingId);
            }

            for (int i = 0; i < num - greetingIdList.size(); i++) {
                int greetingId = RandomHelper.getRandomKeyByWeight(weightMap);
                greetingIdList.add(greetingId);
                weightMap.remove(greetingId);
            }
        }

        return greetingIdList;
    }

    public List<Property> getGuideSceneProperty() {
        return guideSceneProperty;
    }

    public void setGuideSceneProperty(List<Property> guideSceneProperty) {
        this.guideSceneProperty = guideSceneProperty;
    }

    public List<List<Integer>> getGuideInitSelectItemList() {
        return guideInitSelectItemList;
    }

    public void setGuideInitSelectItemList(List<List<Integer>> guideInitSelectItemList) {
        this.guideInitSelectItemList = guideInitSelectItemList;
    }

    public Map<Integer, Integer> getToken2RandomPool() {
        return new HashMap<>(token2RandomPool);
    }

    public void setToken2RandomPool(Map<Integer, Integer> token2RandomPool) {
        this.token2RandomPool = token2RandomPool;
    }
}
